﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    /// <summary>
    /// 点击作者名称进行查询
    /// </summary>
    public partial class SearchBookAuthorPage : PhoneApplicationPage
    {
        private string searchKeyword = string.Empty;
        private string searchType = string.Empty;

        private int pageIndex = 0;
        private bool IsLastPage = false;
        private JsonSearchAuthorItem currentSelectedItem = null;
        // 数据加载的标识
        public bool IsLoading = false;
        // 线程锁的对象
        private object o = new object();
        private bool IsNeedReloadData = false;


        public SearchBookAuthorPage()
        {
            InitializeComponent();
            this.IsNeedReloadData = true;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.IsNeedReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (!base.NavigationContext.QueryString.ContainsKey("searchKeyword"))
            {
                base.NavigationService.GoBack();
                return;
            }
            searchKeyword = base.NavigationContext.QueryString["searchKeyword"];
            if (string.IsNullOrWhiteSpace(searchKeyword))
            {
                base.NavigationService.GoBack();
                return;
            }
            if (!base.NavigationContext.QueryString.ContainsKey("searchType"))
            {
                base.NavigationService.GoBack();
                return;
            }
            searchKeyword = Uri.UnescapeDataString(searchKeyword);
            searchType = base.NavigationContext.QueryString["searchType"];
            if (string.IsNullOrWhiteSpace(searchKeyword))
            {
                base.NavigationService.GoBack();
                return;
            }

            this.txtTitle.Text = searchKeyword;
            //
            if (this.IsNeedReloadData)
                LoadBooksByAuthor(searchKeyword, searchType);
        }


        public void LoadBooksByAuthor(string searchKeyword, string searchType, int pageIndex = 0)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            //comic/searchbookauthor?pindex=0&version=2&psize=10&e=1418028919&name=%E5%94%90%E5%AE%B6%E4%B8%89%E5%B0%91&type=2&channelid=91store
            string requestUrl = string.Concat(KEYS.REQUEST_HOST,
                string.Format("/comic/searchbookauthor?name={0}&type={1}&pindex={2}&psize=10&version=2", Uri.EscapeDataString(searchKeyword), searchType, pageIndex),
                "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonSearchAuthor>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Data != null && rootCharacterString.Info.Data.Totalcount > 0))
                {
                    MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var datasource = rootCharacterString.Info.Data;
                    int total = 0;
                    if (datasource != null && datasource.Items != null && datasource.Items.Count > 0)
                    {
                        total = datasource.Totalcount;
                        this.BindBooksByAuthor(datasource.Items);
                    }
                    this.txtTotalInfo.Text = string.Format("共有 {0} 条结果！", total);
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //

                        if (result.IndexOf("\"items\":{}") >= 0)
                        {
                            IsLastPage = true;
                            if (pageIndex > 0)
                            {
                                //加载更多时给予的提示
                            }
                            else
                            {
                                //搜索结果为空时可能会出现“data”：{”items“:{}} 注意这不是[]
                                MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                            }
                            return;
                        }
                        var rootCharacterString = JSONHelper.Deserialize<JsonSearchAuthor>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Data != null && rootCharacterString.Info.Data.Totalcount > 0))
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var datasource = rootCharacterString.Info.Data;
                            int total = 0;
                            if (datasource != null && datasource.Items != null && datasource.Items.Count > 0)
                            {
                                total = datasource.Totalcount;
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                this.BindBooksByAuthor(datasource.Items);
                            }
                            this.txtTotalInfo.Text = string.Format("共有 {0} 条结果！", total);
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindBooksByAuthor(ObservableCollection<JsonSearchAuthorItem> items)
        {
            if (!(items != null && items.Count > 0))
                return;
            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.llsBooks.ItemsSource != null && this.llsBooks.ItemsSource.Count > 0)
                {
                    foreach (var item in items)
                    {
                        this.llsBooks.ItemsSource.Add(item);
                    }
                }
                else
                {
                    this.llsBooks.ItemsSource = items;
                }
            });
        }



        private void llsBooks_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            lock (o)
            {
                if (IsLoading)
                    return;
                if (e.ItemKind != LongListSelectorItemKind.Item)
                    return;
                currentSelectedItem = e.Container.Content as JsonSearchAuthorItem;
                int selectedIndex = this.llsBooks.ItemsSource.IndexOf(currentSelectedItem);
                int total = this.llsBooks.ItemsSource.Count;
                if (total - selectedIndex <= 2)
                {
                    // 设置IsLoading为true，在加载数据的过程中，禁止多次进入
                    IsLoading = true;
                    if (IsLastPage)
                    {
                        MessageToastManager.Show(AppResources.DataLoading);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                    else
                    {
                        this.pageIndex += 1;
                        this.LoadBooksByAuthor(searchKeyword, searchType, pageIndex);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                }
            }
        }

        private void llsBooks_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            JsonSearchAuthorItem item = this.llsBooks.SelectedItem as JsonSearchAuthorItem;
            if (item != null)
            {
                //NaviService.Navigate(ComicIslandPage.ComicDetailPage, string.Concat("?comicId=", item.Id));
                NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.Id));
            }
        }

        private void Grid_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Complete();
            if (e.CumulativeManipulation.Translation.Y > 0)
            {
                //从下往上拉时不处理
                return;
            }

            if (IsLastPage)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    Helper.PageShowDataNoMore<JsonSearchAuthorItem>(sender, this.llsBooks);
                });
            }
        }
    }
}